package com.xoa.service.cms;

import com.xoa.dao.cms.CmsDocumentInfoMapper;
import com.xoa.model.cms.CmsChannelInfo;
import com.xoa.model.cms.CmsDocumentInfoWithBLOBs;
import com.xoa.model.cms.CmsSiteInfo;
import com.xoa.model.cms.SiteTemplateModel;
import com.xoa.model.enclosure.Attachment;
import com.xoa.service.cms.core.CmsTemplateUtil;
import com.xoa.service.cms.core.FileUtils;
import com.xoa.service.enclosure.EnclosureService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Created by cyt on 2018/7/7.
 */
@Service
public class CmsDocumentPublishService {

    @Autowired
    private CmsSiteService siteService;

    @Autowired
    private CmsSiteTemplateService siteTemplateService;

    @Autowired
    private CmsChannelService channelService;


    @Autowired
    private CmsChannelPublishService channelPublishService;

    @Autowired
    private CmsDocumentService documentService;

    @Autowired
    private EnclosureService attachmentService;

    @Autowired
    CmsDocumentInfoMapper cmsDocumentInfoMapper;
    /**
     * 文章发布
     * @param chnlDocId
     * @param fullPub
     */
    public void toPub(HttpServletRequest request,int chnlDocId, boolean fullPub) throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
        Map cd = documentService.getDocumentByChnlDocId(chnlDocId);
        CmsChannelInfo channelInfo = null;
        channelInfo = channelService.getChannelInfo(FileUtils.getInteger(cd.get("chnlId0"), 0));
        CmsSiteInfo siteInfoModel = siteService.getSiteInfo(channelInfo.getSiteId());
        //获取站点模板
        SiteTemplateModel detailTpl = siteTemplateService.getSiteTemplate(channelInfo.getDetailTpl());
        if(detailTpl!=null){//如果存在首页模板，则进行渲染
            //String path = TeeSysProps.getSiteTemplatePath()+ File.separator+detailTpl.getSiteId();
//            ResourceBundle rb =  ResourceBundle.getBundle("cms");
            String pathsrc=request.getRealPath("cmstpls");
            String path = pathsrc+ System.getProperty("file.separator")+detailTpl.getSiteId();
            Configuration config=new Configuration();
            ByteArrayOutputStream baos = null;
            Writer out = null;
            FileOutputStream fos=null;
            try {
                config.setDirectoryForTemplateLoading(new File(path));

                //注入服务
                config.setCustomAttribute("siteService", siteService);
                config.setCustomAttribute("siteTemplateService", siteTemplateService);
                config.setCustomAttribute("channelService", channelService);
                config.setCustomAttribute("documentService", documentService);
                config.setCustomAttribute("attachmentService", attachmentService);
                config.setCustomAttribute("preview", false);
                //附加参数
                config.setCustomAttribute("ROOT_PATH", channelService.getChannelRootPath(channelInfo.getSid()));
                config.setCustomAttribute("SITE_ID", channelInfo.getSiteId());
                config.setCustomAttribute("CHANNEL_ID", channelInfo.getSid());
                config.setSharedVariable("curChannelId", channelInfo.getSid());
                config.setCustomAttribute("DOCUMENT_ID", cd.get("docId"));
                config.setCustomAttribute("CHNLDOC_ID", chnlDocId);


                Template template=config.getTemplate(detailTpl.getTplFileName(),"UTF-8");
                baos = new ByteArrayOutputStream();
                out = new OutputStreamWriter(baos,"UTF-8");

                //输出参数
                template.process(CmsTemplateUtil.getInstance(), out);
                out.flush();
                out.close();

                //生成对应的静态文件
                String outPath = channelService.getChannelAbsolutePath(channelInfo.getSid())+"/";
                File file = new File(outPath);
                if(!file.exists()){
                    file.mkdirs();
                }
                fos = new FileOutputStream(new File(outPath+chnlDocId+"."+siteInfoModel.getPubFileExt()));
                baos.writeTo(fos);

                /**
                 * 更新文章状态为已发
                 */
                CmsDocumentInfoWithBLOBs documentInfo = documentService.getDocumentByDocId((Integer)cd.get("docId"));
                documentInfo.setStatus(4);
                //documentService.getSimpleDaoSupport().update(documentInfo);
                cmsDocumentInfoMapper.updateByPrimaryKeyWithBLOBs(documentInfo);

                if(fullPub){
                    channelPublishService.toPub(request,channelInfo.getSid(), false);
                }


                /*String cmsIndexPath = TeeSysProps.getProps().getProperty("CMS_CONTENT_INDEX_PATH");
                File indexDir = new File(cmsIndexPath);
                if(!indexDir.exists()){
                    indexDir.mkdir();
                }*/

                int index = outPath.indexOf("/", 2);
                outPath = outPath.substring(index+1);
                String url = channelService.getChannelRootPath(channelInfo.getSid())+outPath+chnlDocId+"."+siteInfoModel.getPubFileExt();
                //System.out.println(url);
//			    createIndex(cmsIndexPath,documentInfo,url);


                CmsSiteInfo siteInfo = siteService.getSiteInfo(channelInfo.getSiteId());
                //获取附件并发布到对应的目录中
                List<Attachment> attaches =null;
               /* attaches =documentService.getAttachmentDao().getAttaches(TeeAttachmentModelKeys.cms, String.valueOf(cd.get("docId")));
                for (TeeAttachment attach : attaches) {
                    String srcPath = attach.getAttachSpace().getSpacePath()+"/"+attach.getModel()+"/"+attach.getAttachmentPath()+"/"+attach.getAttachmentName();
                    InputStream ins = new FileInputStream(srcPath);
                    String destPath=siteInfo.getFolder()+"/attach/"+attach.getModel()+"/"+attach.getAttachmentPath()+"/"+attach.getAttachmentName();
                    TeeUploadHelper.saveFile(ins, destPath);
                    ins.close();
                }

                //获取缩略图并发布到对应目录
                TeeAttachment thumbnail = attachmentService.getById((Integer)cd.get("thumbnail"));
                if(thumbnail!=null){
                    String srcPath = thumbnail.getAttachSpace().getSpacePath()+"/"+thumbnail.getModel()+"/"+thumbnail.getAttachmentPath()+"/"+thumbnail.getAttachmentName();
                    InputStream ins = new FileInputStream(srcPath);
                    String destPath=siteInfo.getFolder()+"/attach/"+thumbnail.getModel()+"/"+thumbnail.getAttachmentPath()+"/"+thumbnail.getAttachmentName();
                    TeeUploadHelper.saveFile(ins, destPath);
                    ins.close();
                }*/

            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                if(baos!=null){
                    try {
                        baos.close();
                    } catch (IOException e) {
                    }
                }
                if(out!=null){
                    try {
                        out.close();
                    } catch (IOException e) {
                    }
                }
                if(fos!=null){
                    try {
                        fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }



    public static String FileReaderAll(String FileName, String charset)throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(FileName), charset));
        String line = new String();
        String temp = new String();
        while ((line = reader.readLine()) != null) {
            temp += line;
        }
        reader.close();
        return temp;
    }
}
